<template>
  <div class="folder-wrapper">
    <div class="folder-header">
      <a-space :size="16">
        <a-input v-model="searchValue" placeholder="组织部门" allow-clear />
        <a-button type="primary" shape="circle" @click="dialogVisible = true">
          <icon-plus />
        </a-button>
      </a-space>
    </div>
    <a-tree
      key="id"
      blockNode
      :data="tableData"
      :field-names="fieldNames"
      @select="handleSelect">
      <template #extra="nodeData">
        <a-dropdown @select="handleSelect(nodeData)">
          <IconMore
            style="position: absolute; top: 10px; right: 8px; font-size: 12px;"
          />
          <template #content>
            <a-doption>新建部门</a-doption>
            <a-doption>重命名</a-doption>
            <a-doption>删除</a-doption>
          </template>
        </a-dropdown>
      </template>

    </a-tree>
    <!--  添加 编辑  -->
    <a-modal
      v-model:visible="dialogVisible"
      title="创建文件夹"
      width="420px"
      :footer="false"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        auto-label-width
        @of="handleSubmit"
      >
        <a-form-item label="上级分类" prop="parent_id">
          <a-tree-select
            v-model="formState.parent_id"
            node-key="id"
            :props="fieldNames"
            :tree-data="departOptions"
            placeholder="请选择上级分类"
            allow-clear
            check-strictly
            check-on-click-node />
        </a-form-item>

        <a-form-item label="文件夹名" prop="name">
          <a-input v-model="formState.name" placeholder="请输入文件夹名"></a-input>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 16, offset: 6 }">
          <a-button type="primary" html-type="submit">确 定</a-button>
          <a-button @click="handleCancel">取 消</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import { IconMore } from "@arco-design/web-vue/es/icon";
import get from "lodash/get";
import { createDepartment, deleteDepartment, getDepartmentList, updateDepartment } from "@/api/system/dept.ts";

import useLoading from "@/hooks/loading";

const emits = defineEmits(["change"]);

interface Tree {
  id?: string;
  name: string;
  children?: Tree[];
}

const fieldNames = {
  key: "id",
  title: "name",
  children: "children"
};

const searchValue = ref("");
const activeKey = ref(0);

// const filterNode = (value: string, data: Tree) => {
//   if (!value) return true
//   return data.name.includes(value)
// }

const handleSelect = (selectedKeys, { selected, node }) => {
  // console.log(selectedKeys, selected, node)
  // 选中
  if (selected) {
    activeKey.value = node.id;
  } else {
    activeKey.value = 0;
  }
  // 只更新folder_id
  emits("change", JSON.parse(JSON.stringify(activeKey.value)));
};

const { loading, setLoading } = useLoading(true);
const tableData = ref([]);
const departOptions = ref([]);

async function fetchTableData() {
  setLoading(true);
  try {
    const { data } = await getDepartmentList();
    tableData.value = data || [];
    departOptions.value = data || [];
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
}

onMounted(() => {
  fetchTableData();
});

// 创建编辑弹窗
const dialogVisible = ref(false);
const formRef = ref();
const formState = reactive({
  id: "",
  parent_id: 0,
  name: ""
});

const formRules = reactive({
  name: [{ required: true, min: 2, max: 10, message: "分组名2~10个字符", trigger: "change" }]
});

// 添加
// function handleAdd(parentId) {
//   if (parentId) {
//     formState.parent_id = parentId
//   }
//   dialogVisible.value = true
// }

// 重命名
// function handleEdit(rowData) {
//   if (rowData.id) {
//     dialogVisible.value = true
//     formState.id = rowData.id
//     formState.parent_id = rowData.parent_id
//     formState.name = rowData.name
//   }
// }


// 取消
const handleCancel = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  dialogVisible.value = false;
};

const handleSubmit = async () => {
  try {
    const params = {
      ...formState
    };

    let result = {};
    if (params.id) {
      result = await updateDepartment(params);
    } else {
      result = await createDepartment(params);
    }

    const { code, msg } = result;

    Message.success(msg || "更新成功！");
    fetchTableData();
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};
</script>

<style scoped lang="less">
.folder-wrapper {
  height: 100%;
  padding: 8px;
  background-color: #fff;

  .folder-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }
}
</style>
